<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Banner;
use app\common\model\Goods as ModelGoods;
use app\common\model\Point as ModelPoint;
use app\common\model\Pointorder;
use app\common\model\Review;
use app\common\model\ScoreLog;
use app\common\model\user\Address;
use think\Db;
use think\Exception;

use function PHPSTORM_META\type;

/**
 * 积分商品接口
 */
class Point extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    /**
     * 商品列表
     *
     */
    public function goodsList()
    {
        $list = ModelPoint::paginate();
        $this->success('请求成功', $list);
    }
    /**
     * 商品详情
     *
     */
    public function goodsInfo()
    {
        $get = $this->request->get();
        extract($get);
        if (!isset($id)) {
            $this->error('参数错误');
        }
        $goods = ModelPoint::get($id);

        $this->success('请求成功', $goods);
    }


    /**
     * 确认订单
     *
     */
    public function orderConfirm()
    {
        $param = request()->param();
        $uid = $this->auth->id;
        extract($param);
        if (!isset($id) || !$id) {
            $this->error('参数错误');
        }
        $goods = ModelPoint::get($id)->toArray();
        if (!$goods) {
            $this->error('商品不存在');
        }
        $num = $num ? $num : 1;
        $goods['totalPoint'] = bcmul($goods['point'], $num);
        $goods['total'] = $num;
        $goods['user_id'] = $uid;
        //地址信息
        if (isset($address_id) && !empty($address_id)) {
            $addressInfo = Address::get([$address_id])->toArray();
            $goods['addressInfo'] = $addressInfo;
            $goods['address_id']  = $address_id;
        } else {
            $addressInfo = Address::getDefaultAddress($uid);
            if ($addressInfo) {
                $goods['addressInfo'] = $addressInfo;
                $goods['address_id']  = $addressInfo['id'];
            }
        }
        $userinfo = $this->auth->getUser();
        if ($userinfo['score'] < $goods['totalPoint']) {
            $this->error('积分不足');
        }
        Db::startTrans();
        try {
            if ($type == 'add') {
                $res = Pointorder::addOrder($goods);
                if ($res) {
                    ScoreLog::income($uid, $goods['totalPoint'], 1, 100, $res['sn']);
                }
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('兑换成功', $type == 'add' ? $res : $goods);
    }

    /**
     * 兑换记录
     *
     */
    public function log()
    {
        $list = Pointorder::where('user_id', $this->auth->id)->order('id desc')->paginate();
        $this->success('',$list);
    }
}
